/*=====================================================
Critical Links
Auto Configuration Server

Authors:
	Rui Eduardo Gouveia Gil - r-gil@critical-links.com

Date: 2011
Version 0.1
=======================================================*/
DeviceWindow = function(group) {
	this.group = group;
	this.device;
    this.deviceName = new Ext.form.TextField({
        fieldLabel: "Device Name",
        width: 314,
        validationEvent: false,
        validateOnBlur: false,
        msgTarget: "under",
        mode: "local",
        listeners:{scope: this}
    });

    this.deviceLicense = new Ext.form.TextField({
        fieldLabel: "Device License",
        width: 314,
        validationEvent: false,
        validateOnBlur: false,
        msgTarget: "under",
        mode: "local",
        listeners:{scope: this}
    });
    
    this.deviceConfiguration = new Ext.form.ComboBox({
        fieldLabel: "Device Configuration",
        width: 314,
        editable: false,
        validationEvent: false,
        validateOnBlur: false,
        msgTarget: "under",
        triggerAction: "all",
        valueField: "id",
        displayField: "text",
        mode: "local",
        listeners:{scope: this},
        store: new Ext.data.ArrayStore({fields: ["id", "text"]})
    });
    
    this.deviceConfigurationMode = new Ext.form.ComboBox({
        fieldLabel: "Device Configuration Mode",
        width: 314,
        editable: false,
        validationEvent: false,
        validateOnBlur: false,
        msgTarget: "under",
        triggerAction: "all",
        valueField: "id",
        displayField: "text",
        mode: "local",
        listeners:{scope: this},
        store: new Ext.data.ArrayStore({fields: ["id", "text"], data: [["0", "Automatic First Config"], ["1", "Force Automatic"], ["2", "Automatic"], ["3", "Manual"]]})
    });

 	this.deviceBeginLabel = new Ext.form.Label({text: "From", style:"background:transparent;margin-top: 7px;"});
 
    this.deviceBegin = new Ext.form.TextField({
        emptyText: "eg. 0:00 or 0:00pm",
        width: 120,
        validationEvent: false,
        validateOnBlur: false,
        mode: "local",
        style:"margin-left: 10px;",
        listeners:{scope: this}
    });

 	this.deviceEndLabel = new Ext.form.Label({text: "to", style:"background:transparent;margin-top: 7px;margin-left: 10px;"});

    this.deviceEnd = new Ext.form.TextField({
        emptyText: "eg. 5:00 or 5:00pm",
        width: 120,
        validationEvent: false,
        validateOnBlur: false,
        mode: "local",
        style:"margin-left: 10px;",
        listeners:{scope: this}
    });

    this.devicePeriod = new Ext.Panel({
		layout:"column",
        fieldLabel: "Operation time",
        items: [this.deviceBeginLabel,this.deviceBegin,this.deviceEndLabel,this.deviceEnd],
        border: false,
        bodyStyle:"background:transparent;"
    });

    this.deviceDescription = new Ext.form.TextArea({
        fieldLabel: "Device Description",
        emptyText: "",
        width: 314,
        validationEvent: false,
        validateOnBlur: false,
        msgTarget: "under",
        mode: "local",
        listeners:{scope: this}
    });

    this.form = new Ext.FormPanel({
        labelAlign:"top",
        items: [this.deviceName,this.deviceLicense,this.deviceConfiguration,this.deviceConfigurationMode,this.devicePeriod,this.deviceDescription],
        border: false,
        bodyStyle:"background:transparent;padding:10px;"
    });

	DeviceWindow.superclass.constructor.call(this, {
        title: "Create New Device",
        iconCls: "device-icon",
        autoHeight: true,
        width: 350,
        resizable: false,
        plain:true,
        modal: true,
        y: 100,
        autoScroll: false,
        closeAction: "hide",

        buttons:[{
            text: "Create",
            handler: this.onCreate,
            scope: this
        },{
            text: "Save",
            handler: this.onSave,
            scope: this
        },{
            text: "Cancel",
            handler: this.hide.createDelegate(this, [])
        }],

        items: this.form
    });
    
}

Ext.extend(DeviceWindow, Ext.Window, {
    
    show : function(device){
        this.device = device;
        
	    this.populateConfiguration();

        if(this.device) {
        	this.setTitle("Edit Device");
        	this.deviceName.setValue(this.device.name);
        	this.deviceLicense.setValue(this.device.licenseID);
        	this.deviceDescription.setValue(this.device.description);
        	this.deviceConfigurationMode.setValue(this.device.configMode);
        	if(this.device.actionPeriod.length == 0)
        	{
	        	this.deviceBegin.setValue("0:00");
				this.deviceEnd.setValue("23:59");
        	}
        	else
        	{
        		var begin = this.device.actionPeriod.substr(0,this.device.actionPeriod.indexOf(" "));
        		var end = this.device.actionPeriod.substr(this.device.actionPeriod.indexOf(" ")+1);
	        	this.deviceBegin.setValue(begin);
				this.deviceEnd.setValue(end);
        	}
        	this.buttons[0].hide();
        	this.buttons[1].show();
        } else {
        	this.setTitle("Create New Device");
        	this.deviceName.setValue("");
        	this.deviceLicense.setValue("");
        	this.deviceConfiguration.setValue("");
        	this.deviceDescription.setValue("");
        	this.deviceConfigurationMode.setValue("0");
        	this.deviceBegin.setValue("0:00");
			this.deviceEnd.setValue("23:59");
        	this.buttons[1].hide();
        	this.buttons[0].show();
        }

        DeviceWindow.superclass.show.apply(this, arguments);
    },

    onCreate: function() {
    	var aserror = 0;

		if(this.deviceName.getValue() == "") {
       		this.deviceName.markInvalid("Invalid device name!");
       		aserror = 1;
		}
    	
		if(this.deviceLicense.getValue() == "") {
       		this.deviceLicense.markInvalid("Invalid device license!");
       		aserror = 1;
		}
    	
		if(this.deviceConfiguration.getValue() == "") {
       		this.deviceConfiguration.markInvalid("Invalid device configuration!");
       		aserror = 1;
		}
    	
		if(this.deviceConfigurationMode.getValue() == "") {
       		this.deviceConfigurationMode.markInvalid("Invalid device configuration mode!");
       		aserror = 1;
		}

     	var str = checkTime(this.deviceBegin.getValue());
		if(str != "") {
       		this.deviceBegin.markInvalid(str);
       		aserror = 1;
		}
    	
    	str = checkTime(this.deviceEnd.getValue());
		if(str != "") {
       		this.deviceEnd.markInvalid(str);
       		aserror = 1;
		}
 
    	if(aserror == 0) {
	        this.el.mask("Creating New Device...", "x-mask-loading");
       		SGui.createDevice(this.deviceName.getValue(), this.deviceLicense.getValue(), this.deviceConfiguration.getValue(), this.deviceConfigurationMode.getValue(), this.group.id, this.deviceDescription.getValue(), this.deviceBegin.getValue()+" "+this.deviceEnd.getValue(),this.validateDeviceCreate, this);
		}
    },

    onSave: function() {
    	var aserror = 0;

		if(this.deviceName.getValue() == "") {
       		this.deviceName.markInvalid("Invalid device name!");
       		aserror = 1;
		}
    	
		if(this.deviceLicense.getValue() == "") {
       		this.deviceLicense.markInvalid("Invalid device license!");
       		aserror = 1;
		}
    	
		if(this.deviceConfiguration.getValue() == "") {
       		this.deviceConfiguration.markInvalid("Invalid device configuration!");
       		aserror = 1;
		}
    	
		if(this.deviceConfigurationMode.getValue() == "") {
       		this.deviceConfigurationMode.markInvalid("Invalid device configuration mode!");
       		aserror = 1;
		}
    	
    	var str = checkTime(this.deviceBegin.getValue());
		if(str != "") {
       		this.deviceBegin.markInvalid(str);
       		aserror = 1;
		}
    	
    	str = checkTime(this.deviceEnd.getValue());
		if(str != "") {
       		this.deviceEnd.markInvalid(str);
       		aserror = 1;
		}
		
    	if(aserror == 0) {
	        this.el.mask("Saving Device...", "x-mask-loading");
       		SGui.saveDevice(this.device.id,this.deviceName.getValue(), this.deviceLicense.getValue(), this.deviceConfiguration.getValue(), this.deviceConfigurationMode.getValue(), this.device.groupID, this.deviceDescription.getValue(), this.deviceBegin.getValue()+" "+this.deviceEnd.getValue(), this.validateDeviceSave, this);
		}
    },

    markInvalid : function(msg){
        this.deviceName.markInvalid(msg);
        this.el.unmask();
    },

    validateDeviceCreate: function(obj,result){
    	if(result.length > 1) {
    		if(result[0] == "1") {
                obj.el.unmask();
                obj.hide();
   				return obj.fireEvent("createdevice", result[1]);
    		} else {
    			obj.markInvalid(result[1]);
    		}    		
    	} else {
    		alert("Invalid Protocol From Server...");
    	}
	},

    validateDeviceSave: function(obj,result){
    	if(result.length > 1) {
    		if(result[0] == "1") {
                obj.el.unmask();
                obj.hide();
   				return obj.fireEvent("savedevice", result[1]);
    		} else {
    			obj.markInvalid(result[1]);
    		}    		
    	} else {
    		alert("Invalid Protocol From Server...");
    	}
	},

	populateConfiguration : function(){
		SGui.getConfigurations(this.cbPopulateConfiguration,this);
	},

	cbPopulateConfiguration : function(obj,result){
		obj.deviceConfiguration.store.removeAll();
		if(result) {	
			if(result instanceof Array) {			
				for(var i=0; i<result.length; i++) {
					var configuration = new Configuration(result[i]);
					obj.deviceConfiguration.store.loadData([[configuration.id,configuration.name,configuration]],true);
				}
			} else {
				var configuration = new Configuration(result);
				obj.deviceConfiguration.store.loadData([[configuration.id,configuration.name,configuration]],true);
			}
			
			if(obj.device) {
				obj.deviceConfiguration.setValue(obj.device.configID);
			}
		}
		
	}
});
